package com.lin.util;

import java.text.MessageFormat;
import java.util.*;

/**
 * Class loading and holding the contents of com.lin.trains.properties.
 */
public class PropertyFactory {
    private static final Map<String, String> properties = new HashMap<>();

    // Load property file.
    static {
        loadProperties();
    }

    /**
     * Load properties from file.
     */
    private static void loadProperties() {
        try {
            properties.clear();

            Locale defaultLocale = Locale.getDefault();
            ResourceBundle props = ResourceBundle.getBundle("com.lin.trains", defaultLocale);

            for (Object key : props.keySet()) {
                String keyStr = key.toString();
                properties.put(keyStr, props.getString(keyStr));
            }

        } catch (MissingResourceException e) {
            throw new IllegalArgumentException("trains.properties file not found!");
        }
    }
    private PropertyFactory() {

    }

    public static Map<String, String> getProperties() {
        return properties;
    }

    public static String propertyWithArgs(String property, Object... arguments) {
        String propertyValue = getProperties().get(property);

        if (propertyValue == null) {
            throw new IllegalArgumentException("Property for key '" + property + "' not found!");
        } else {
            MessageFormat formatter = new MessageFormat("");
            formatter.applyPattern(propertyValue);
            String output = formatter.format(arguments);

            return output;
        }
    }


    public static void main(String[] args) {
        new PropertyFactory();
    }
}
